package com.bawei.room_test;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

/**
 * entities:表
 * version：数据库版本
 * exportSchema：是否导出Schema文件
 */
@Database(entities = {Student.class,Goods.class},version = 4,exportSchema = true)
public abstract class AppDataBase extends RoomDatabase {
//构造千万不要私有化
//    private AppDataBase(){}
    private static AppDataBase appDataBase;
    public static AppDataBase getInstance(){
        if(appDataBase == null){
            synchronized (AppDataBase.class){
                if(appDataBase == null){
                    //实例化数据库对象
                    appDataBase = Room.databaseBuilder(App.instance,AppDataBase.class, "student.db")
                            .allowMainThreadQueries()//数据库默认认为耗时操作，主线程操作数据库必须添加
                            .createFromAsset("student.db")//预填充数据，从assets目录中读取数据
//                          .fallbackToDestructiveMigration()//数据库重新创建，会将之前用户操作存储的数据全部清空，初始状态
                            .addMigrations(MIGRATION_1_2)
                            .addMigrations(MIGRATION_2_3)
                            .addMigrations(MIGRATION_3_4)
                            .build();
                }
            }
        }
        return appDataBase;
    }
    //提供dao：注意抽象方法
    private StudentDao mStudentDao;
    public abstract StudentDao getStudentDao();
    //1->2:增加sex字段
    static final Migration MIGRATION_1_2 = new Migration(1,2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE student2 ADD COLUMN sex INTEGER NOT NULL DEFAULT 1 ");
        }
    };
    //2->3:销毁与重建策略：将sex字段INTEGER改成TEXT
    static final Migration MIGRATION_2_3 = new Migration(2,3) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //创建一张临时表
            database.execSQL("CREATE TABLE temp_student (" +
                    "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"+
                    "username TEXT,"+
                    "age INTEGER NOT NULL,"+
                    "sex TEXT DEFAULT 'M')"
            );
            //将旧表中的数据复制到新表
            database.execSQL("INSERT INTO temp_student (username,age,sex)" +
                    "SELECT username,age,sex FROM student2");
            //旧表删除
            database.execSQL("DROP TABLE student2");
            //将新表名称改为student2
            database.execSQL("ALTER TABLE temp_student RENAME TO student2");
        }
    };
    //3->4:新增表
    static final Migration MIGRATION_3_4 = new Migration(3,4) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("c");
        }
    };





}
